package cn.e3.sso.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3.mapper.TbUserMapper;
import cn.e3.pojo.TbUser;
import cn.e3.pojo.TbUserExample;
import cn.e3.pojo.TbUserExample.Criteria;
import cn.e3.sso.service.RegisterCheck;
import cn.e3.utils.E3Result;
@Service
public class RegisterCheckImpl implements RegisterCheck {
	@Autowired
	private TbUserMapper userMapper;
	@Override
	public E3Result registerCheck(String param, Integer type) {
		//创建查询条件
		TbUserExample example=new TbUserExample();
		Criteria criteria = example.createCriteria();
		//判断参数类型，1=用户名,2=手机号，3=邮箱
		if(type==1){
			criteria.andUsernameEqualTo(param);
		}else if(type==2){
			criteria.andPhoneEqualTo(param);
		}else if(type==3){
			criteria.andEmailEqualTo(param);
		}else{
			return E3Result.ok("数据异常");
		}
		List<TbUser> list = userMapper.selectByExample(example);
		if(list!=null&&list.size()>0){
			return E3Result.ok(false);
		}
		return E3Result.ok(true);
	}
	/*
	 * 用户登录
	 */
	public E3Result register(TbUser user) {
		//判断参数是否有效
		if(StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())||StringUtils.isBlank(user.getPhone())){
			return E3Result.build(400, "参数错误");
		}
		//判断用户名与手机号是否被占用
		E3Result result = registerCheck(user.getUsername(), 1);
		if(!(boolean) result.getData()){
			return E3Result.build(400, "用户名被占用");
		}
		result=registerCheck(user.getPhone(), 2);
		if(!(boolean) result.getData()){
			return E3Result.build(400, "手机号被占用");
		}
		//补全pojo
		user.setCreated(new Date());
		user.setUpdated(new Date());
		//密码加密，利用spring自制的
		String md5password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
		//将封装的md5密码封装到pojo
		user.setPassword(md5password);
		int i = userMapper.insert(user);
		if(i>0){
			return E3Result.ok(true);
		}
		return E3Result.ok(false);
	}

}
